import android.os.Handler
import android.os.Looper
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.retrofit.FastLoadingObserver
import com.aries.library.fast.retrofit.FastObserver
import com.aries.library.fast.util.FastStackUtil
import com.aries.library.fast.util.ToastUtil
import com.dcjt.firehotcarpad.entity.BaseEntity
import com.dcjt.firehotcarpad.entity.CarZZXX
import com.dcjt.firehotcarpad.entity.EventEntity
import com.dcjt.firehotcarpad.entity.InstructionListEntity
import com.dcjt.firehotcarpad.helper.CountDownDialogHelper
import com.dcjt.firehotcarpad.manager.DataManager
import com.dcjt.firehotcarpad.manager.TtsManager
import com.dcjt.firehotcarpad.model.SendMessageUtils
import com.dcjt.firehotcarpad.moudle.HandleDisasterActivity
import com.dcjt.firehotcarpad.moudle.NavActivity
import com.dcjt.firehotcarpad.retrofit1.repository.ApiRepository1
import com.dcjt.firehotcarpad.utils.StringUtils
import com.google.gson.Gson
import com.trello.rxlifecycle2.android.ActivityEvent
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity
import per.goweii.rxhttp.kt.download.utils.RxNotify.runOnUiThread
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


/**
 * Created by cj on 2021/2/22.
 * Email:codesexy@163.com
 * Function:
 * desc:为整个应用提供车辆状态服务
 */
class NewMessagePool private constructor(
    private val mDispatchEngine: ExecutorService = Executors.newSingleThreadExecutor(),
    private val mHandler: Handler = Handler(Looper.getMainLooper())
) {


    private var observers: MutableList<NewMessageObserverObserver> = mutableListOf()

    companion object {
        private var instance: NewMessagePool? = null
            get() {
                if (field == null) {
                    field = NewMessagePool()
                }
                return field
            }

        fun get(): NewMessagePool {
            return instance!!
        }
    }


    /**
     * 开始分发消息
     */
    fun sendDispatch(data: EventEntity.MessageDetailEvent) {
        //弹出框框  点击点确定 再分发
        //弹出弹出框
        var msTts:String = ""
        when(data.flag){
            //指令消息
            DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.zhzX_RWZL -> {
                onObserverMessageZl(data.obj as InstructionListEntity,1)
            }
            //收到新的车辆调度信息
            DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_CLZT_ZNZHDP -> {
                msTts = "收到新的车辆调度信息"

            }
            //车辆状态改变的消息
            DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_CLZT_SET -> {
                    CarStatePool.get().getCarState(true)
            }
            //新的警情消息
            DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_ZQXX_SAVE -> {
                msTts = ""
                getZqxxDetail(data, msTts,data.flag)
            }
            //"收到新的作战位置"
            DataManager.getInstance().appConfigEntity.znzh_pmqEnum.znzH_TB_Cmd.tB_ZZBH_RWXD ->{
                msTts = "收到新的作战位置"
                //作战位置弹框判断
                //判断是否是 导航界面   1.是： 直接： 语音提醒（收到新的作战位置）
                // 2.否：（1.当前警情：弹框（收到新的作战位置，是否立即前往？）是（20s）：直接跳转导航界面， 否：取消
                //      2. 非当前警情： 弹框（警情:地址+灾情等级+灾情类型，收到新的作战位置，是否立即前往？）是（20s）：直接跳转导航界面， 否：取消）
                getZqxxDetail(data, msTts,data.flag)

            }
        }
    }

    /**
     * 分发指令消息
     */
     fun onObserverMessageZl(entity : InstructionListEntity,flag:Int) {
         //0表示列表弹框   1表示 接受到的新消息
         if (entity.sfzyy!= null&&entity.sfzyy == 1 && flag == 1){
             TtsManager.get().speeckTTs("收到新指令：${entity.zlnr}")
         }

         CountDownDialogHelper.showInstructionCountDownDialog(
             FastStackUtil.getInstance().current,
             entity,
             if (entity.dwzlzt?.toInt() == 3) "" else "签收",
             callback = {
                 Thread(Runnable {
                     var data =  Gson().toJson(hashMapOf(Pair("zlzt","3"),Pair("jsdwid",DataManager.getInstance().user.id)))

                     ApiRepository1.getInstance().uploadInstructionState(entity.id.toString(),data)
                         .compose((FastStackUtil.getInstance().current as RxAppCompatActivity).bindUntilEvent(
                             ActivityEvent.DESTROY))
                         .subscribe(object :  FastLoadingObserver<Any>(FastStackUtil.getInstance().current) {
                             override fun _onNext(result: Any) {

                                 var result1 = Gson().fromJson(Gson().toJson(result), BaseEntity::class.java)
                                 FastStackUtil.getInstance().current.runOnUiThread(Runnable {
                                     //更新UI
                                     if (result1.code == 200 ){
                                     ToastUtil.show("该指令签收成功")
                                     //发送消息
                                     if(!StringUtils.isEmpty(entity.zqid)) entity.zqid else ""?.let {
                                         SendMessageUtils.get().sendMessage(DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.zhzX_RWZL,
                                             it,FastStackUtil.getInstance().current,entity.id)
                                     }
                                 } else{
                                     ToastUtil.show(result1.msg)
                                 }
                             })

                             //分发刷新指令消息
                             dispatchRefreshZlMessage()
                             }

                             override fun _onError(errorRes: Int, errorCode: Int, e: Throwable) {
                                 super._onError(errorRes, errorCode, e)
                                 LoggerManager.e(e.message)
                                 FastStackUtil.getInstance().current.runOnUiThread(Runnable {
                                     //更新UI
                                     ToastUtil.show("该指令签收失败")
                                 })
                                 //分发刷新指令消息
                                 dispatchRefreshZlMessage()
                             }
                         })
                 }).start()

             },cancelCallback = {

             })


    }

    private fun dispatchRefreshZlMessage() {
        mDispatchEngine.submit {
            try {
                observers.forEach {
                    mHandler.post {
                        try {
                            it.onMessageZLnRefresh()
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 分发集结点位置  消息
     */
     fun onObserverMessageJjd(data: EventEntity.MessageDetailEvent) {
        mDispatchEngine.submit {
            try {
                observers.forEach {
                    mHandler.post {
                        try {
                            it.onMessageJjdLocation(data)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }


    }

    public fun sendUploadBiaohuiDispatch(
        zqid: String
    ) {
        mDispatchEngine.submit {
            try {
                observers.forEach {
                    mHandler.post {
                        try {
                            it.onUploadBiaoHuiMessage(zqid)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

        }
    }
    /**
     * 获取警情详情
     */
    private fun getZqxxDetail(
        data: EventEntity.MessageDetailEvent,
        msTts: String,flag: String
    ) {
        var msTts1 = msTts
        ApiRepository1.getInstance().getCarZuozhanXX(data.zqId)
            .subscribe(object : FastObserver<CarZZXX>() {

                override fun _onError(errorRes: Int, errorCode: Int, e: Throwable) {
                    super._onError(errorRes, errorCode, e)
                    ToastUtil.show("获取车辆作战信息失败")
                    e.printStackTrace()
                }

                override fun _onNext(it: CarZZXX) {
                    if (it != null && !StringUtils.isEmpty(it.zqxx!!.gisX)) {
                        when(data.flag){
                            //收到新的车辆调度信息
                            DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_CLZT_ZNZHDP -> {}
                            //新的警情消息
                            DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_ZQXX_SAVE -> {
                                msTts1 =
                                    "有新警情：在${it.zqxx!!.xzqmc}${it.zqxx!!.sfdz}发生${it.zqxx!!.ajdjmc}${it.zqxx!!.ajlxmc}，是否立即前往？"
                            }
                            //"收到新的作战位置"
                            DataManager.getInstance().appConfigEntity.znzh_pmqEnum.znzH_TB_Cmd.tB_ZZBH_RWXD ->{

                                //作战位置弹框判断
                                //判断是否是 导航界面   1.是： 直接： 语音提醒（收到新的作战位置）
                                // 2.否：（1.当前警情：弹框（收到新的作战位置，是否立即前往？）是（20s）：直接跳转导航界面， 否：取消
                                //      2. 非当前警情： 弹框（警情:地址+灾情等级+灾情类型，收到新的作战位置，是否立即前往？）是（20s）：直接跳转导航界面， 否：取消）

                                if (FastStackUtil.getInstance().current.javaClass == NavActivity::class.java) {
                                    msTts1 = "收到新的作战位置"
                                    TtsManager.get().speeckTTs(msTts)
                                    return
                                } else {
                                    msTts1 = if (FastStackUtil.getInstance().current.javaClass == HandleDisasterActivity::class.java
                                        && data.zqId == CarStatePool.get().getCurrentZqidPage()
                                        && (if (CarStatePool.get().getCarStateDetail()?.clxx?.ywjq!!) CarStatePool.get().getCarStateDetail()?.clxx?.jqid else "") == CarStatePool.get().getCurrentZqidPage()){
                                        "收到新的作战位置"
                                    }else{
                                        "警情：${it.zqxx!!.sfdz}${it.zqxx!!.ajdjmc}${it.zqxx!!.ajlxmc}，收到新的作战位置，是否立即前往？"
                                    }
                                }
                            }
                        }
                        //弹出弹出框
                        observeMessage(msTts1, data)
                    }
                }
            })
    }


    fun onReceiveDocumentMsg() {
        mDispatchEngine.submit {
            try {
                observers.forEach {
                    mHandler.post {
                        try {
                            it.onReceiveFireDocument()
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

        }
    }

    /**
     * 弹框并  分发消息
     */
    private fun observeMessage(msTts: String, data: EventEntity.MessageDetailEvent) {
        TtsManager.get().speeckTTs(msTts)

        CountDownDialogHelper.showCountDownDialog(
            FastStackUtil.getInstance().current,
            "提醒",
            msTts,
            "确定",
            callback = {
                mDispatchEngine.submit {
                    try {
                        observers.forEach {
                            mHandler.post {
                                try {
                                    when(data.flag){
                                        //收到新的车辆调度信息
                                        DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_CLZT_ZNZHDP -> {
                                            it.onCarDiaodu(data)
                                        }
                                        //新的警情消息
                                        DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_ZQXX_SAVE -> {
                                            it.onNewDisasterMessage(data)
                                            it.onRefreshList()
                                        }
                                        //"收到新的作战位置"
                                        DataManager.getInstance().appConfigEntity.znzh_pmqEnum.znzH_TB_Cmd.tB_ZZBH_RWXD ->{
                                            it.onCarLocationChange(data)
                                        }
                                    }

                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

            },cancelCallback = {
                mDispatchEngine.submit {
                    try {
                        observers.forEach {
                            mHandler.post {
                                try {
                                    when(data.flag){
                                        //新的警情消息
                                        DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_ZQXX_SAVE -> {
                                            it.onRefreshList()
                                        }
                                    }
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }


            })
    }


    fun registerNewMessageObserver(observer: NewMessageObserverObserver) {
        observers.add(observer)
    }


    fun unRegisterNewMessageObserver(observer: NewMessageObserverObserver) {
        observers.remove(observer)
    }


    interface NewMessageObserverObserver {
        //新警情
        fun onNewDisasterMessage(data: EventEntity.MessageDetailEvent) {}

        //作战位改变
        fun onCarLocationChange(data: EventEntity.MessageDetailEvent) {}
        fun onCarDiaodu(data: EventEntity.MessageDetailEvent) {}
        fun onRefreshList(){}
        //指令消息刷新
        fun onMessageZLnRefresh(){}
        //新的现场文书通知
        fun onReceiveFireDocument() {}
        //新的集结点位置
        fun onMessageJjdLocation(data: EventEntity.MessageDetailEvent){}
        fun onUploadBiaoHuiMessage( zqid: String){}

    }


}